package com.tim.source.templete;

import java.io.InputStream;

import com.tim.source.MakeSource;
import com.tim.source.common.CommonInfo;
import com.tim.source.common.TableInfo;
import com.tim.source.util.StringUtil;

public class SpringBeanProc {
	// Spring 模板文件.
	private static String TEMPLETE;
	// Spring Bean模板文件.
	private static String BEAN_TEMPLETE;
	// Spring Bean配置文件内容
	private static String SPRING_BEAN_CONTENT;
	static {
		// 获取Spring模板文件
		TEMPLETE = getPartString("springBean");

		// 获取Spring Bean模板文件
		BEAN_TEMPLETE = getPartString("bean");
		// 替换作者
		BEAN_TEMPLETE = BEAN_TEMPLETE.replace("%author%", CommonInfo.AUTHOR);
		// 替换时间
		BEAN_TEMPLETE = BEAN_TEMPLETE.replace("%dateTime%",
				CommonInfo.DATESTRING);

		// 获取现有Spring Bean配置文件
		SPRING_BEAN_CONTENT = StringUtil.fileToString(MakeSource.SPRING_BEAN);
	}

	private static String getPartString(String partStr) {
		try {
			// 加载hbm尾部模板
			InputStream part = SpringBeanProc.class.getResourceAsStream(partStr
					+ ".tmp");
			byte[] partData = new byte[part.available()];
			part.read(partData);
			part.close();
			return new String(partData, "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public static String execute() {
		// 空配置文件 || 不存在.
		if ("".equals(SPRING_BEAN_CONTENT)
				|| SPRING_BEAN_CONTENT.indexOf(TableToServiceImpl.FULL_CLASS) == -1) {
			// 替换Entity类名.
			String tempStr = BEAN_TEMPLETE.replace("%className%",
					TableInfo.className);
			// 替换tableProperty
			tempStr = tempStr.replace("%tableProperty%", TableInfo
					.getTableProperty());
			// 替换ServiceImpl
			tempStr = tempStr.replace("%fullServiceImpl%",
					TableToServiceImpl.FULL_CLASS);
			// 替换DaoImpl
			tempStr = tempStr.replace("%fullDaoImpl%",
					TableToDaoImpl.FULL_CLASS);
			return tempStr;
		}
		return null;
	}

	public static String getBeanString(String tempStr) {
		tempStr = tempStr + "</beans>";
		if ("".equals(SPRING_BEAN_CONTENT))
			return TEMPLETE.replace("</beans>", tempStr);
		else
			return SPRING_BEAN_CONTENT.replace("</beans>", tempStr);
	}
}
